package com.xudow.app.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.qanda.Answer;
import com.activeshare.edu.ucenter.models.qanda.Question;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.model.qanda.P2PMessage;
import com.xudow.app.ui.adapter.qanda.P2PQuestionAdapter;
import com.xudow.app.ui.task.qanda.QuestionDetailTask;
import com.xudow.app.ui.task.qanda.QuestionSubmitSelfAnswerTask;
import com.xudow.app.ui.task.qanda.QuestionSubmitTask;
import com.xudow.app.util.Lists;
import com.xudow.app.util.Maps;
import com.xudow.app.util.MessageUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 单独提问Activity
 *
 * @author lukecheng
 */
public class P2PQuestionActivity extends BaseActivity {

    private long expertId;
    private long questionId = 0L;

    private TextView questionView;
    private ListView questionListView;

    private List<P2PMessage> p2pMessages;
    private P2PQuestionAdapter p2pQuestionAdapter;

    private QuestionSubmitTask questionSubmitTask;
    private QuestionDetailTask questionDetailTask;
    private QuestionSubmitSelfAnswerTask questionSubmitSelfAnswerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_p2p_question);

        expertId = getIntent().getLongExtra("expertId", 0L);
        questionId = getIntent().getLongExtra("questionId", 0L);

        questionView = (TextView) findViewById(R.id.question);
        questionListView = (ListView) findViewById(R.id.question_list);

        p2pMessages = Lists.newArrayList();
        p2pQuestionAdapter = new P2PQuestionAdapter(this, android.R.layout.simple_list_item_1, p2pMessages);

        questionListView.setAdapter(p2pQuestionAdapter);

        if (questionId > 0) {
            loadQuestionDetail();
        }
    }

    private void loadQuestionDetail() {
        HashMap<String, String> params = Maps.newHashMap();
        params.put("question_id", Long.toString(questionId));

        questionDetailTask = new QuestionDetailTask(this, questionDetailTaskHandler);
        addTask(questionDetailTask);
        questionDetailTask.execute(params);
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (null != questionSubmitTask && !questionSubmitTask.isCancelled()) {
                questionSubmitTask.cancel(true);
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 发送按钮点击
     *
     * @param view
     */
    public void onSendClick(View view) {
        String question = questionView.getText().toString().trim();

        if (TextUtils.isEmpty(question)) {
            questionView.setError("请输入问题");
            return;
        }

        showLodingDialog(getString(R.string.submitting));

        if (questionId <= 0) {
            HashMap<String, String> params = Maps.newHashMap();
            params.put("question", question);
            params.put("expert_id", Long.toString(expertId));

            questionSubmitTask = new QuestionSubmitTask(this, questionSubmitTaskHandler);
            questionSubmitTask.execute(params);
        } else {
            HashMap<String, String> params = Maps.newHashMap();
            params.put("answer", question);
            params.put("question_id", Long.toString(questionId));

            questionSubmitSelfAnswerTask = new QuestionSubmitSelfAnswerTask(this, questionSubmitSelfAnswerTaskHandler);
            questionSubmitSelfAnswerTask.execute(params);
        }
    }

    private Handler questionSubmitTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (QuestionSubmitTask.SUCCESS == msg.what) {
                Long qid = msg.getData().getLong("questionId", 0L);

                if (qid > 0) {
                    questionId = qid;

                    loadQuestionDetail();
                }

                questionView.setText("");
            } else {
                String message = getString(R.string.submit_fail);
                Toast.makeText(P2PQuestionActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    private Handler questionSubmitSelfAnswerTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (QuestionSubmitTask.SUCCESS == msg.what) {
                P2PMessage pm = new P2PMessage();
                pm.portraitUrl = p2pMessages.get(0).portraitUrl;
                pm.userProfileId = p2pMessages.get(0).userProfileId;
                pm.isExpert = false;
                pm.time = MessageUtils.formatTimeStampString(P2PQuestionActivity.this, new Date());
                pm.message = questionView.getText().toString();

                p2pMessages.add(pm);
                p2pQuestionAdapter.notifyDataSetInvalidated();

                questionListView.smoothScrollToPosition(questionListView.getCount() - 1);

                questionView.setText("");
            } else {
                String message = getString(R.string.submit_fail);
                Toast.makeText(P2PQuestionActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    private Handler questionDetailTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (QuestionDetailTask.SUCCESS == msg.what) {
                Question[] dataArr = (Question[]) msg.getData().getSerializable("questions");

                if (null == dataArr || dataArr.length <= 0) {
                    return;
                }

                Question q = dataArr[0];
                P2PMessage pmQuestion = new P2PMessage();

                String portraitUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, q.getUserProfile().getPhotoPath());
                pmQuestion.portraitUrl = portraitUrl;

                pmQuestion.username = q.getUserProfile().getName();
                pmQuestion.message = q.getQuestion();

                String time = MessageUtils.formatTimeStampString(P2PQuestionActivity.this, q.getCreateTime());
                pmQuestion.time = time;
                pmQuestion.userProfileId = q.getUserProfileId();
                pmQuestion.isExpert = false;

                p2pMessages.add(pmQuestion);

                List<Answer> answers = q.getAnswers();

                for (Answer a : answers) {
                    P2PMessage pm = new P2PMessage();

                    pm.isExpert = (pmQuestion.userProfileId != a.getUserProfile().getId());

                    if (pm.isExpert) {
                        pm.portraitUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, q.getExpert().getPhotoPath());
                    } else {
                        pm.portraitUrl = pmQuestion.portraitUrl;
                    }

                    pm.time = MessageUtils.formatTimeStampString(P2PQuestionActivity.this, a.getCreateTime());
                    pm.username = a.getUserProfile().getName();
                    pm.message = a.getAnswer();

                    p2pMessages.add(pm);
                }

                p2pQuestionAdapter.notifyDataSetChanged();

                questionListView.smoothScrollToPosition(questionListView.getCount() - 1);
            }
        }
    };

}
